package cn.leon.controller;

import cn.leon.common.pojo.JsonUtils;
import cn.leon.utils.FastDFSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Controller
public class PictureController {

    @Value("${IMAGE_SERVER_URL}")
    private String IMAGE_SERVER_URL;

    @RequestMapping(value = "/pic/upload" ,produces = MediaType.TEXT_PLAIN_VALUE + ";charset=utf-8")
    @ResponseBody
    public String uploadPic(MultipartFile uploadFile){
        try {
            byte[] content = uploadFile.getBytes();
            //取文件的扩展名
            String filename = uploadFile.getOriginalFilename();
            String ext = filename.substring(filename.lastIndexOf(".") + 1);
            //把文件内容上传到图片服务器
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:resource/fast_dfs.conf");
            //执行长传处理
            String path = fastDFSClient.uploadFile(content, ext);
            System.out.println(IMAGE_SERVER_URL + path);
            Map result = new HashMap();
            result.put("error",0);
            result.put("url", IMAGE_SERVER_URL + path);
            return JsonUtils.objectToJson(result);
        } catch (Exception e) {
            e.printStackTrace();
            Map result = new HashMap();
            result.put("error", 1);
            result.put("url", "图片上传失败");
            return JsonUtils.objectToJson(result);
        }
    }
}
